<template>
  <div class="card content-box">
    <el-form ref="ruleFormRef" :rules="rules" :model="addRequestTaskFormData" style="width: 100%" label-width="122px">
      <el-button type="primary" @click="onSubmitForm(ruleFormRef)"> 保存 </el-button>
      <el-button type="primary" @click="backList"> 返回列表 </el-button>
      <!-- <el-button type="primary" @click="serviceDir"> 服务目录 </el-button> -->
      <el-dialog title="选择服务目录" v-model="dialogServiceDirTableVisible">
        <div :style="{ height: '500px' }">
          <Custemerselect @send-data="sendCompanyNoData" />
        </div>
      </el-dialog>
      <div>
        <p>基本信息</p>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item class="item" label="所属客户 :" prop="companyName" style="width: 48%">
            <el-input v-model="addRequestTaskFormData.companyName" @click="dialogCompanyNoTableVisible = true" />
            <el-dialog title="选择客户" v-model="dialogCompanyNoTableVisible">
              <div :style="{ height: '500px' }">
                <Custemerselect @send-data="sendCompanyNoData" />
              </div>
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="item" label="请求用户 :" prop="createdByName" style="width: 48%">
            <el-input v-model="addRequestTaskFormData.createdByName" @click="dialogCreatedByTableVisible = true" />
            <el-dialog title="选择用户" v-model="dialogCreatedByTableVisible">
              <div :style="{ height: '500px' }">
                <Userselect @send-data="sendCreatedByData" :father="fatherValue" />
              </div>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="item" label="请求分类 :" prop="requestCategoryName" style="width: 48%">
            <el-tree-select
              ref="RequestType"
              v-model="requestCategorySelectValue"
              :data="requestCategorySelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeRequestType"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="item" label="标题 :" prop="etitle" style="width: 48%">
            <el-input v-model="addRequestTaskFormData.etitle" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="item" label="描述 :" style="width: 1200px">
        <WangEditor v-model:value="content" height="400px" />
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item class="item" label="来源 :" style="width: 48%">
            <el-tree-select
              v-model="imodeSelectValue"
              :data="imodeSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeimode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="item" label="优先级 :" style="width: 48%">
            <el-tree-select
              v-model="prioritySelectValue"
              :data="prioritySelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changepriority"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="item" label="影响 :" style="width: 48%">
            <el-tree-select
              v-model="effectRangeSelectValue"
              :data="effectRangeSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeeffectRange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="item" label="复杂程度 :" style="width: 48%">
            <el-tree-select
              v-model="levelSelectValue"
              :data="levelSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changelevel"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="item" label="紧急度 :" style="width: 48%">
            <el-tree-select
              v-model="seriousnessSelectValue"
              :data="seriousnessSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeseriousness"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="item" label="位置 :" style="width: 48%">
            <el-tree-select
              v-model="LocationSelectValue"
              :data="LocationSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeLocation"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName">
        <el-tab-pane label="关联配置项" name="first">
          <el-button type="primary" @click="selectCiDialogVisible = true"> 添加 </el-button>
          <el-dialog title="选择关联配置项" v-model="selectCiDialogVisible">
            <div :style="{ height: '500px' }">
              <moreSelectCi @send-data="sendCiData" />
            </div>
          </el-dialog>
          <ProTable
            ref="ciProTable"
            row-key="id"
            :indent="20"
            :data="ciList"
            :columns="ciColumns"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          >
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link @click="deleteci(scope.$index)">删除</el-button>
            </template>
          </ProTable>
        </el-tab-pane>
        <el-tab-pane label="附件" name="second">
          <el-button type="primary" @click="addAttachment"> 添加附件 </el-button>
          <ProTable
            ref="attachmentProTable"
            row-key="id"
            :indent="20"
            :data="attachmentList"
            :columns="attachmentColumns"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          >
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link @click="deleteattachment(scope.$index)">删除</el-button>
            </template>
          </ProTable>
        </el-tab-pane>
        <el-tab-pane label="时间表设定" name="third">
          <div :style="{ height: '620px' }">
            <el-form style="width: 100%" label-width="120px">
              <el-form-item label="" prop="etitle">
                <table style="width: 100%">
                  <tr>
                    <td><el-radio v-model="addRequestTaskFormData.timeType" label="day">日计划</el-radio></td>
                    <td><el-radio v-model="addRequestTaskFormData.timeType" label="weekly">周计划</el-radio></td>
                    <td><el-radio v-model="addRequestTaskFormData.timeType" label="month">月计划</el-radio></td>
                  </tr>
                  <tr>
                    <td><el-radio v-model="addRequestTaskFormData.timeType" label="cycle">周期性计划（天）</el-radio></td>
                    <td><el-radio v-model="addRequestTaskFormData.timeType" label="cycleMinute">周期性计划（分钟）</el-radio></td>
                    <td><el-radio v-model="addRequestTaskFormData.timeType" label="on_off">一次性计划</el-radio></td>
                  </tr>
                </table>
              </el-form-item>

              <div v-if="addRequestTaskFormData.timeType == `day`">
                <el-form-item label="[每日定时任务]"> </el-form-item>
                <el-form-item label="开始时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskDate"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="结束时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskEndDate"
                    type="datetime"
                    placeholder="请选择结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="具体时间 :">
                  <el-input-number v-model="addRequestTaskFormData.taskHour" :min="0" :max="23" />点
                  <el-input-number v-model="addRequestTaskFormData.taskMinute" :min="0" :max="59" />分
                </el-form-item>
              </div>
              <div v-if="addRequestTaskFormData.timeType == `weekly`">
                <el-form-item label="[每周定时任务]"> </el-form-item>
                <el-form-item label="">
                  <table style="width: 100%">
                    <tr>
                      <td><el-checkbox v-model="meizhou" label="selectmeizhou" @change="changeMeizhou">每周：</el-checkbox></td>
                    </tr>
                    <tr>
                      <td><el-checkbox v-model="addRequestTaskFormData.MON" label="MON">星期一</el-checkbox></td>
                      <td><el-checkbox v-model="addRequestTaskFormData.TUE" label="TUE">星期二</el-checkbox></td>
                      <td><el-checkbox v-model="addRequestTaskFormData.WED" label="WED">星期三</el-checkbox></td>
                      <td><el-checkbox v-model="addRequestTaskFormData.THU" label="THU">星期四</el-checkbox></td>
                    </tr>
                    <tr>
                      <td><el-checkbox v-model="addRequestTaskFormData.FRI" label="FRI">星期五</el-checkbox></td>
                      <td><el-checkbox v-model="addRequestTaskFormData.SAT" label="SAT">星期六</el-checkbox></td>
                      <td><el-checkbox v-model="addRequestTaskFormData.SUN" label="SUN">星期天</el-checkbox></td>
                    </tr>
                  </table>
                </el-form-item>
                <el-form-item label="开始时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskDate"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="结束时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskEndDate"
                    type="datetime"
                    placeholder="请选择结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="具体时间 :">
                  <el-input-number v-model="addRequestTaskFormData.taskHour" :min="0" :max="23" />点
                  <el-input-number v-model="addRequestTaskFormData.taskMinute" :min="0" :max="59" />分
                </el-form-item>
              </div>

              <div v-if="addRequestTaskFormData.timeType == `month`">
                <el-form-item label="[每月定时任务]   ">
                  <el-checkbox v-model="meiyue" label="selectmeiyue" @change="changeMeiyue">每月：</el-checkbox>
                </el-form-item>
                <el-form-item label="">
                  <table style="width: 100%">
                    <!-- <tr>
          		  							   <td><el-checkbox v-model="meiyue" label="selectmeiyue"  @change="changeMeiyue">每月：</el-checkbox></td>
          		  						   </tr> -->
                    <tr>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.JAN" label="JAN" @change="changeYue">一月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.FEB" label="FEB" @change="changeYue">二月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.MAR" label="MAR" @change="changeYue">三月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.APR" label="APR" @change="changeYue">四月</el-checkbox>
                      </td>
                    </tr>
                    <tr>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.MAY" label="MAY" @change="changeYue">五月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.JUN" label="JUN" @change="changeYue">六月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.JUL" label="JUL" @change="changeYue">七月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.AUG" label="AUG" @change="changeYue">八月</el-checkbox>
                      </td>
                    </tr>
                    <tr>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.SEP" label="SEP" @change="changeYue">九月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.OCT" label="OCT" @change="changeYue">十月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.NOV" label="NOV" @change="changeYue">十一月</el-checkbox>
                      </td>
                      <td>
                        <el-checkbox v-model="addRequestTaskFormData.DEC" label="DEC" @change="changeYue">十二月</el-checkbox>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="4">
                        <div class="no-wrap">
                          日期：
                          <el-select v-model="addRequestTaskFormData.monthDay" placeholder="Select" style="width: 100px">
                            <el-option v-for="item in monthDayNum" :key="item" :label="item" :value="item" />
                          </el-select>
                        </div>
                        <span> </span>
                      </td>
                    </tr>
                  </table>
                </el-form-item>
                <el-form-item label="具体时间 :">
                  <el-input-number v-model="addRequestTaskFormData.taskHour" :min="0" :max="23" />点
                  <el-input-number v-model="addRequestTaskFormData.taskMinute" :min="0" :max="59" />分
                </el-form-item>
              </div>
              <div v-if="addRequestTaskFormData.timeType == `cycle`">
                <el-form-item label="[周期性计划(天)]"> </el-form-item>
                <el-form-item label="每">
                  <el-input-number v-model="addRequestTaskFormData.cyclicalDay" :min="1" :max="99999" />天执行一次
                </el-form-item>
                <el-form-item label="开始时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskDate"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="结束时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskEndDate"
                    type="datetime"
                    placeholder="请选择结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="具体时间 :">
                  <el-input-number v-model="addRequestTaskFormData.taskHour" :min="0" :max="23" />点
                  <el-input-number v-model="addRequestTaskFormData.taskMinute" :min="0" :max="59" />分
                </el-form-item>
              </div>
              <div v-if="addRequestTaskFormData.timeType == `cycleMinute`">
                <el-form-item label="[周期性计划(分钟)]"> </el-form-item>
                <el-form-item label="每">
                  <el-input-number v-model="addRequestTaskFormData.cyclicalMinute" :min="1" :max="99999" />分钟执行一次
                </el-form-item>
                <el-form-item label="开始时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskDate"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="结束时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskEndDate"
                    type="datetime"
                    placeholder="请选择结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </div>
              <div v-if="addRequestTaskFormData.timeType == `on_off`">
                <el-form-item label="[只执行一次]"> </el-form-item>
                <el-form-item label="开始时间 :">
                  <el-date-picker
                    v-model="addRequestTaskFormData.taskDate"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item label="具体时间 :">
                  <el-input-number v-model="addRequestTaskFormData.taskHour" :min="0" :max="23" />点
                  <el-input-number v-model="addRequestTaskFormData.taskMinute" :min="0" :max="59" />分
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="ts" name="basicForm">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref, reactive, onMounted, onBeforeUnmount, defineComponent } from "vue";
import { getjggl, emailtest, emailtestexchange, testSMSAccount, getjgglmessage, mergeCompany } from "@/api/modules/jggl";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
import { isTelOrFax, isEmail } from "@/utils/eleValidate";
import WangEditor from "@/components/WangEditor/index.vue";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";
import { useRoute, useRouter } from "vue-router";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import {
  findPageScheduledTask,
  saveScheduledTask,
  deleteScheduledTask,
  findScheduledTaskById,
  editScheduledTask,
  uploadFile
} from "@/api/modules/systemTools";
import { useTabsStore } from "@/stores/modules/tabs";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import moreSelectCi from "@/views/tools/moreCiSelect/index.vue";
import ImportExcel from "@/views/tools/uploadFile/index.vue";
import { getCurrentLoginUser } from "@/api/modules/accessController";
const content = ref("");
const router = useRouter();
const route = useRoute();
const tabStore = useTabsStore();
const UserselectRef = ref<InstanceType<typeof Userselect> | null>(null);

//关联配置项开始
const ciProTable = ref<ProTableInstance>();
const ciList = ref<any>([]);
const selectCiDialogVisible = ref(false);
const ciColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "cino", label: "固定资产编号", sortable: true },
  { prop: "ciname", label: "名称", sortable: true, width: 260 },
  { prop: "categoryName", label: "分类", sortable: true, width: 260 },
  { prop: "status", label: "状态", sortable: true, width: 260 },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);

// 删除
const deleteci = async (index: any) => {
  ciList.value.splice(index, 1);
};

//选中资产子组件弹窗回调方法
const sendCiData = (data: [resCIList]) => {
  if (data.length > 0) {
    for (let i = 0; i < data.length; i++) {
      //去重
      let addflag = true;
      ciList.value.forEach(val => {
        if (val.ciId == data[i].ciId) {
          addflag = false;
        }
      });
      if (addflag == true) {
        ciList.value.push(data[i]);
      } else {
        ElMessage({
          type: "info",
          message: "存在相同配置 :   " + data[i]["ciname"] + "，  已自动过滤重复配置"
        });
      }
    }
  }
  selectCiDialogVisible.value = false;
};
export interface resCIList {
  ciname: string;
  cino: string;
  categoryName: string;
  categoryNo: string;
  status: string;
  ciId: number;
  attachmentStr: string;
  fileName: string;
  beginTime: string;
  companyName: string;
  companyNo: number;
  contractName: string;
  contractNo: number;
  dataFlag: number;
  description: string;
  dialect: string;
  endTime: string;
  finishTime: number;
  flagName: string;
  lastUpdater: string;
  packageName: string;
  respondTime: number;
  ruleName: string;
  ruleNo: number;
  rulePackageNo: number;
  salience: number;
  showFinishTime: string;
  showRespondTime: string;
  beforeOrAfter: boolean;
  beforeOrAfterStr: string;
  timeStr: string;
}
//关联配置项结束

//附件开始
const attachmentProTable = ref<ProTableInstance>();
const attachmentList = ref<any>([]);
const attachmentColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "fileName", label: "文件名称" },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);
const uploadFileRes = async (param: any) => {
  let res = JSON.parse(JSON.stringify(param));
  let attachmentStr = res.fileName + "==" + res.msg + "==" + res.fileSize + "-s-";
  let attachment = {
    fileName: res.fileName,
    attachmentStr: attachmentStr
  };
  attachmentList.value.push(attachment);
};
// 添加附件
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const addAttachment = () => {
  const params = {
    title: "",
    tempApi: uploadFile,
    importApi: uploadFile,
    getTableList: ciProTable.value?.getTableList,
    addAttachmentMethod: uploadFileRes
  };
  dialogRef.value?.acceptParams(params);
};
// 删除附件
const deleteattachment = async (index: any) => {
  attachmentList.value.splice(index, 1);
};
//附件结束

//时间表开始
const meizhou = ref("");
const meiyue = ref("");
const monthDayNum = ref(31);

const scheduledTaskType = ref("request");
const dialogTableVisible = ref(false);
const dialogAddDtlVisible = ref(false);
const AddDtlName = ref("");
const TaskOption = ref("");

const changeYue = async value => {
  addRequestTaskFormData.monthDay = 1;
  if (addRequestTaskFormData.FEB == true) {
    monthDayNum.value = 28;
  } else {
    if (
      addRequestTaskFormData.APR == true ||
      addRequestTaskFormData.JUN == true ||
      addRequestTaskFormData.SEP == true ||
      addRequestTaskFormData.NOV == true
    ) {
      monthDayNum.value = 30;
    } else {
      monthDayNum.value = 31;
    }
  }
};
// 每月是否选择
const changeMeiyue = async value => {
  if (value == true) {
    addRequestTaskFormData.JAN = true;
    addRequestTaskFormData.FEB = true;
    addRequestTaskFormData.MAR = true;
    addRequestTaskFormData.APR = true;
    addRequestTaskFormData.MAY = true;
    addRequestTaskFormData.JUN = true;
    addRequestTaskFormData.JUL = true;
    addRequestTaskFormData.AUG = true;
    addRequestTaskFormData.SEP = true;
    addRequestTaskFormData.OCT = true;
    addRequestTaskFormData.NOV = true;
    addRequestTaskFormData.DEC = true;
  } else {
    addRequestTaskFormData.JAN = false;
    addRequestTaskFormData.FEB = false;
    addRequestTaskFormData.MAR = false;
    addRequestTaskFormData.APR = false;
    addRequestTaskFormData.MAY = false;
    addRequestTaskFormData.JUN = false;
    addRequestTaskFormData.JUL = false;
    addRequestTaskFormData.AUG = false;
    addRequestTaskFormData.SEP = false;
    addRequestTaskFormData.OCT = false;
    addRequestTaskFormData.NOV = false;
    addRequestTaskFormData.DEC = false;
  }
};
// 每周是否选择
const changeMeizhou = async value => {
  if (value == true) {
    addRequestTaskFormData.MON = true;
    addRequestTaskFormData.TUE = true;
    addRequestTaskFormData.WED = true;
    addRequestTaskFormData.THU = true;
    addRequestTaskFormData.FRI = true;
    addRequestTaskFormData.SAT = true;
    addRequestTaskFormData.SUN = true;
  } else {
    addRequestTaskFormData.MON = false;
    addRequestTaskFormData.TUE = false;
    addRequestTaskFormData.WED = false;
    addRequestTaskFormData.THU = false;
    addRequestTaskFormData.FRI = false;
    addRequestTaskFormData.SAT = false;
    addRequestTaskFormData.SUN = false;
  }
};
//时间表结束

//开始
//请求客户
const dialogCompanyNoTableVisible = ref(false);
const dialogCreatedByTableVisible = ref(false); //创建人
const requestCategorySelectValue = ref();
const requestCategorySelectList = ref<any>([]);
//来源选择开始
const imodeSelectValue = ref();
const imodeSelectList = ref<any>([]);
const changeimode = (val: any) => {
  imodeSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTaskFormData.imodeNo = newElement.dcode;
    }
  });
};
//来源选择结束
//优先级选择开始
const prioritySelectValue = ref();
const prioritySelectList = ref<any>([]);
const changepriority = (val: any) => {
  prioritySelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTaskFormData.priorityNo = newElement.dcode;
    }
  });
};
//优先级选择结束
//影响选择开始
const effectRangeSelectValue = ref();
const effectRangeSelectList = ref<any>([]);
const changeeffectRange = (val: any) => {
  effectRangeSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTaskFormData.effectRangeNo = newElement.dcode;
    }
  });
};
//影响结束
//复杂程度选择开始
const levelSelectValue = ref();
const levelSelectList = ref<any>([]);
const changelevel = (val: any) => {
  levelSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTaskFormData.levelNo = newElement.dcode;
    }
  });
};
//紧急度选择开始
const seriousnessSelectValue = ref();
const seriousnessSelectList = ref<any>([]);
const changeseriousness = (val: any) => {
  seriousnessSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addRequestTaskFormData.seriousnessNo = newElement.dcode;
    }
  });
};
//紧急度结束
//紧急度选择开始
const LocationSelectValue = ref();
const LocationSelectList = ref<any>([]);
const changeLocation = (val: any) => {
  if (val == "所在位置") {
    ElMessage.info("当前节点不可选");
    LocationSelectValue.value = addRequestTaskFormData.locationName;
    return;
  }
  traverseTree(LocationSelectList.value[0], node => {
    if (node.value == val.toString()) {
      addRequestTaskFormData.locationNos = node.attr.id;
      addRequestTaskFormData.locationName = node.attr.cname;
    }
  });
};
// 父组件的值
const fatherValue = ref({ orgNo: 1 });

const addRequestTaskFormData = reactive({
  reportId: 0,
  scheduledTaskId: "",
  scheduledTaskType: "request",
  beanId: "autoUpdateRequestJob",
  companyNo: 1,
  etitle: "",
  timeType: "day",
  cyclicalDay: 1,
  cyclicalMinute: 1,
  taskDate: "",
  taskEndDate: "",
  taskHour: 0,
  taskMinute: 0,
  MON: false,
  TUE: false,
  WED: false,
  THU: false,
  FRI: false,
  SAT: false,
  SUN: false,

  JAN: false,
  FEB: false,
  MAR: false,
  APR: false,
  MAY: false,
  JUN: false,
  JUL: false,
  AUG: false,
  SEP: false,
  OCT: false,
  NOV: false,
  DEC: false,
  monthDay: 1,

  formId: "",
  companyName: "",

  createdByName: "",
  createdByNo: "",
  requestCategoryName: "",
  requestCategoryNo: "",
  edesc: "",
  imodeNo: "",
  priorityNo: "",
  effectRangeNo: "",
  levelNo: "",
  seriousnessNo: "",
  locationName: "",
  locationNos: "",
  attachmentStr: ""
});

//客户选择子组件弹窗回调方法
const sendCompanyNoData = (data: any) => {
  dialogCompanyNoTableVisible.value = false;
  addRequestTaskFormData.companyNo = data.orgNo;
  addRequestTaskFormData.companyName = data.orgName;
  fatherValue.value.orgNo = data.orgNo;
};
//用户选择子组件弹窗回调方法
const sendCreatedByData = (data: any) => {
  dialogCreatedByTableVisible.value = false;
  addRequestTaskFormData.createdByNo = data.userId;
  addRequestTaskFormData.createdByName = data.fullName;
};
// ProTable 实例

//请求分类选择
const changeRequestType = (val: any) => {
  traverseTree(requestCategorySelectList.value[0], node => {
    if (node.value == val.toString()) {
      if ((node.children as any).length > 0) {
        // console.log("非叶子节点")
        ElMessage.info("请选择叶子节点");
        requestCategorySelectValue.value = addRequestTaskFormData.requestCategoryName;
      } else {
        addRequestTaskFormData.requestCategoryNo = node.attr.id;
        addRequestTaskFormData.requestCategoryName = node.attr.cname;
        addRequestTaskFormData.etitle = node.attr.cname;
      }
    }
  });
  console.log(val);
};

const onSubmitForm = async (formEl: FormInstance | undefined) => {
  if (content.value == null || content.value == "") {
    ElMessage.error("描述不能为空");
  }

  //时间的判断
  if (addRequestTaskFormData.timeType != "") {
    if (addRequestTaskFormData.timeType == `month`) {
      //月的时候时间不用填
      addRequestTaskFormData.taskDate = "";
      addRequestTaskFormData.taskEndDate = "";
    } else {
      if (addRequestTaskFormData.taskDate == "") {
        ElMessage.error("请选择开始时间");
        activeName.value = "third";
        return;
      }

      if (addRequestTaskFormData.timeType == `on_off`) {
      } else {
        if (addRequestTaskFormData.taskEndDate == "") {
          ElMessage.error("请选择结束时间");
          return;
        }
      }
    }
    if (addRequestTaskFormData.timeType != `on_off`) {
      let taskDate = new Date(addRequestTaskFormData.taskDate);
      let taskEndDate = new Date(addRequestTaskFormData.taskEndDate);
      if (taskDate >= taskEndDate) {
        ElMessage.error("开始时间不能大于结束时间");
        return;
      }
    }

    if (addRequestTaskFormData.timeType != `on_off`) {
      let selsctDate = new Date(addRequestTaskFormData.taskEndDate);
      let year = selsctDate.getFullYear(); // 获取当前年份
      let month = selsctDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
      let day = selsctDate.getDate();
      let selsctTime = new Date(year, month, day);
      let nowDate = new Date();
      let nowDateyear = nowDate.getFullYear(); // 获取当前年份
      let nowDatemonth = nowDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
      let nowDateday = nowDate.getDate();
      let nowTime = new Date(nowDateyear, nowDatemonth, nowDateday);
      if (selsctTime <= nowTime) {
        ElMessage.error("设置的任务执行时间不能早于当前系统时间!");
        return;
      }
    } else {
      let selsctDate = new Date(addRequestTaskFormData.taskDate);
      let year = selsctDate.getFullYear(); // 获取当前年份
      let month = selsctDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
      let day = selsctDate.getDate();
      let selsctTime = new Date(year, month, day);
      let nowDate = new Date();
      let nowDateyear = nowDate.getFullYear(); // 获取当前年份
      let nowDatemonth = nowDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
      let nowDateday = nowDate.getDate();
      let nowTime = new Date(nowDateyear, nowDatemonth, nowDateday);
      if (selsctTime <= nowTime) {
        ElMessage.error("设置的任务执行时间不能早于当前系统时间!");
        return;
      }
    }
  }

  addRequestTaskFormData.edesc = content.value.toString();
  let idsStr = "";
  for (let i = 0; i < ciList.value.length; i++) {
    if (idsStr == "") {
      idsStr = "cinos=" + ciList.value[i].ciId;
    } else {
      idsStr = idsStr + "&cinos=" + ciList.value[i].ciId;
    }
  }
  let attachmentStr = "";
  for (let i = 0; i < attachmentList.value.length; i++) {
    if (attachmentStr == "") {
      attachmentStr = attachmentList.value[i].attachmentStr;
    } else {
      attachmentStr += attachmentList.value[i].attachmentStr;
    }
  }
  addRequestTaskFormData.attachmentStr = attachmentStr;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //校验成功
      saveScheduledTask(addRequestTaskFormData, "scheduledTaskDTO", idsStr).then(res => {
        console.log(res);
        ElMessage.success("新增成功");
        tabStore.removeTabs(route.fullPath);
        router.push(`/system/tools/regularTaskManagement?pageNo=${Math.random().toFixed(3)}`);
      });
      ElMessage.success("保存成功");
    } else {
      ElMessage.error("请正确填写表单");
    }
  });
  console.log(content.value);
  //getjggl(fsyxData, "emailServerDTO");
  // ElMessage.success("提交的发送邮箱数据为 : " + JSON.stringify(addRequestTaskFormData));
};
// 返回列表
const backList = async () => {
  tabStore.removeTabs(route.fullPath);
  router.push(`/system/tools/regularTaskManagement?pageNo=${Math.random().toFixed(3)}`);
};
const dialogServiceDirTableVisible = ref(false);
// 服务目录
const serviceDir = async () => {
  dialogServiceDirTableVisible.value = true;
  tabStore.removeTabs(route.fullPath);
  router.push(`/system/tools/regularTaskManagement?pageNo=${Math.random().toFixed(3)}`);
};

//结束

const ruleFormRef = ref<FormInstance>();
const activeName = ref("first");

const rules = reactive<FormRules>({
  companyName: [{ required: true, message: "请选择公司", trigger: "blur" }],
  createdByName: [{ required: true, message: "请选择请求用户", trigger: "blur" }],
  requestCategoryName: [{ required: true, message: "请选择请求分类", trigger: "blur" }],
  etitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
  edesc: [{ required: true, message: "请输入描述", trigger: "blur" }]
});
onMounted(() => {
  //加载公司信息
  getjgglmessage().then(res => {
    let newParams = JSON.parse(JSON.stringify(res));
    addRequestTaskFormData.companyName = newParams.companyName;
    addRequestTaskFormData.companyNo = newParams.companyNo;
  });
  //加载用户数据
  getCurrentLoginUser().then(res => {
    let newRes = JSON.parse(JSON.stringify(res));
    addRequestTaskFormData.createdByNo = newRes.userId;
    addRequestTaskFormData.createdByName = newRes.fullName;
  });
  //请求分类选择树
  getCategoryTreeAllData("Request").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    let k: any[] = [];
    k.push(res);
    requestCategorySelectList.value = k;
  });
  //来源
  dataDictionaryItemsfindByCode("imode").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    imodeSelectList.value = res as any;
  });
  //优先级priority
  dataDictionaryItemsfindByCode("priority").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    prioritySelectList.value = res as any;
  });
  //影响effectRange
  dataDictionaryItemsfindByCode("effectRange").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    effectRangeSelectList.value = res as any;
  });
  dataDictionaryItemsfindByCode("level").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    levelSelectList.value = res as any;
  });
  dataDictionaryItemsfindByCode("seriousness").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    seriousnessSelectList.value = res as any;
  });
  //位置
  getCategoryTreeAllData("Location").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    LocationSelectList.value = [res as any];
  });
});

interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
</script>

<style scoped lang="scss">
@import "./index";
.item {
  width: 500px;
}
</style>
